class PersonControllerTests extends GroovyTestCase {
	Person user
	PersonController pc
	Role role
	void setUp() {
		// set up PersonController
		pc = new PersonController()
		pc.session.user = null
		// save a user
		role = new Role(name:"role1")
		role.save()
		user = new Person(userName:"user1", password:"password1", firstname:"User1FN", lastname:"User1LN", regNo:"user1Reg", email:"tianjianping@hotmail.com", role:role)
		user.save()
	}
	void tearDown() {
		user.delete()
		role.delete()
	}
	void testBlankUserName() {
		def user = new Person (userName:"")
		assertFalse "there should be errors", user.validate()
		assertTrue "another way to check for errors after you call validate()", user.hasErrors()
	} 
	/** 
	* Test the PersonControler.handleLogin action
	* If the login succeeds, it will put the user object intot he session.
	*/
	void testHandleLogin() {
		// set up controller parameters
		pc.params.userName = user.userName
		pc.params.password = user.password
		// Call the action
		pc.handleLogin()
		// And the user was redirected to the Home page
		assertEquals "/person/home", pc.response.redirectedUrl
	}
	/** 
	* Test the PersonController.handleLogin action.
	* I the login fails, it will redirect to login and set a flash message.
	*/
	void testHandleLoginInvalidUser() {
		// Setup controller parameters
		pc.params.userName = "INVALID_USER_NAME"
		pc.params.password = "INVALID_PASSWORD"
		// Call the action
		pc.handleLogin()
		assertEquals "/person/login", pc.response.redirectedUrl
		def message = pc.flash.message
		assert message
		assert message.startsWith("Login Failed")
	}

	/**
	* Test the PersonController.login action
	* If the logout action succeeds, it will remove the user object from
	* the session.
	*/
	void testLogout() {
		// make it look like user is logged in
		pc.session.user = user
		pc.logout()
		def sessUser = pc.session.user
		assertNull("expected session user to be null", sessUser)
		assertEquals "/person/login", pc.response.redirectedUrl
	}
}		
